package com.hmall.order.task;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hmall.order.mapper.OrderMapper;
import com.hmall.order.pojo.Order;
import lombok.RequiredArgsConstructor;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.List;
import java.util.stream.Collectors;


@Component
@RequiredArgsConstructor
public class ClearOrderTask {
    private final OrderMapper orderMapper;

    @Scheduled(cron = "0 0/1 * * * ? ")
    public void clearOverdueOrder() {

        LambdaQueryWrapper<Order> wrapper = Wrappers.<Order>lambdaQuery().eq(Order::getStatus, 1);
        List<Order> orderList = orderMapper.selectList(wrapper);
        List<Order> overdueOrders = orderList.stream().filter(order -> {
            return order
                    .getCreateTime()
                    .toInstant()
                    .atZone(ZoneId.systemDefault())
                    .toLocalDateTime()
                    .plusSeconds(30)
                    .isBefore(LocalDateTime.now());
        }).collect(Collectors.toList());
        overdueOrders.forEach(order -> {
            //设置订单状态为已取消
            order.setStatus(5);
            //更新数据库
            orderMapper.updateById(order);
        });
    }
}
